package com.docjohnson.pamphlet.activities;

import org.json.JSONObject;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.docjohnson.pamphlet.R;
import com.docjohnson.pamphlet.animation.Rotate3dAnimation;
import com.docjohnson.pamphlet.fragment.FavouriteItemDetailsFragment;
import com.docjohnson.pamphlet.fragment.PamphletDetailsFragment;
import com.docjohnson.pamphlet.models.Pamphlet;
import com.docjohnson.pamphlet.utils.PamphletPreferences;

public class PamphletDetailsActivity extends Activity {

	private static final String FAVOURITE_ITEM_TAG = "favourite.item.tag";
	
	private ImageView leftWingView = null;
	private ImageView rightWingView = null;
	private ImageView rightWingViewOnLeftWing = null;
	private ImageView centerWingImageView = null;
	private RelativeLayout contentView = null;
	private RelativeLayout leftWingLayout = null;
	private RelativeLayout rightWingLayout = null;
	private RelativeLayout centerWingLayout = null;
	private int displayWidth = 0;
	private int displayHeight = 0;
	private Pamphlet pamphlet = null;
	private Bitmap cover = null;
	private Bitmap backgroundLeft = null;
	private Bitmap backgroundRight = null;
	private Bitmap backgroundCenter = null;
	private Bitmap transitionBitmap = null;
	private MediaPlayer sound1 = null;
	private MediaPlayer sound2 = null;
	private int rotationTime = 1500;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.new_android_pamphlet_details_layout);
		
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		displayHeight = (int) (displaymetrics.heightPixels - dipToPixel(80));
		displayWidth = (int) (displaymetrics.widthPixels - dipToPixel(200)); 
		
		leftWingView = (ImageView) findViewById(R.id.left_wing_imageview);
		rightWingView = (ImageView) findViewById(R.id.right_wing_imageview);
		contentView = (RelativeLayout) findViewById(R.id.pamphlet_content_layout);
		leftWingLayout = (RelativeLayout) findViewById(R.id.left_wing_relative_layout);
		rightWingLayout = (RelativeLayout) findViewById(R.id.right_wing_relative_layout);
		rightWingViewOnLeftWing = (ImageView) findViewById(R.id.right_wing_imageview_in_left_wing);
		centerWingImageView = (ImageView) findViewById(R.id.center_wing_imageview);
		centerWingImageView.setVisibility(View.INVISIBLE);
		pamphlet = (Pamphlet) getIntent().getExtras().get("pamphlet");
		
		PamphletPreferences prefs = new PamphletPreferences(getApplicationContext());
		rotationTime = prefs.getRotationSpeed();
		
		BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
		bmpOptions.inSampleSize = pamphlet.inSampleSize;
		cover = BitmapFactory.decodeFile(pamphlet.getLocalImagePath(), bmpOptions);
		leftWingView.setImageBitmap(cover);
		rightWingView.setImageBitmap(cover);
		rightWingViewOnLeftWing.setImageBitmap(cover);
		
		transitionBitmap =  BitmapFactory.decodeFile(pamphlet.getLocalTransitionImagePath(), bmpOptions);
		Bitmap bgBitmap = BitmapFactory.decodeFile(pamphlet.getLocalBackgroundPath(), bmpOptions);
		int bitmapWidth = bgBitmap.getWidth();
		int bitmapHeight = bgBitmap.getHeight();
		Matrix m = new Matrix();
	    m.preScale(-1, 1);
		backgroundLeft = Bitmap.createBitmap(bgBitmap, 0, 0, bitmapWidth/3, bitmapHeight, m, false);
		backgroundCenter = Bitmap.createBitmap(bgBitmap,  bitmapWidth/3, 0,  bitmapWidth/3, bitmapHeight);
		backgroundRight = Bitmap.createBitmap(bgBitmap,  2*bitmapWidth/3, 0,  bitmapWidth/3, bitmapHeight, m , false);
		bgBitmap.recycle();
		bgBitmap = null;
		contentView.post(new Runnable() {

			@Override
			public void run() {
				RelativeLayout.LayoutParams contentViewLayoutParams = (LayoutParams) contentView.getLayoutParams();
				contentViewLayoutParams.width = (int) (displayWidth);
				contentViewLayoutParams.height = (int) (displayHeight);
				contentView.setLayoutParams(contentViewLayoutParams);
				
//				RelativeLayout.LayoutParams leftWingLayoutParams = (LayoutParams) leftWingLayout.getLayoutParams();
//				leftWingLayoutParams.width = contentView.getWidth()/2;
//				leftWingLayout.setLayoutParams(leftWingLayoutParams);
//				
//				RelativeLayout.LayoutParams rightWingLayoutParams = (LayoutParams) rightWingLayout.getLayoutParams();
//				rightWingLayoutParams.width = contentView.getWidth()/2;
//				rightWingLayout.setLayoutParams(rightWingLayoutParams);
//				
//				RelativeLayout.LayoutParams leftWingImageViewLayoutParams = (LayoutParams) leftWingView.getLayoutParams();
//				leftWingImageViewLayoutParams.width = contentView.getWidth()/4;
//				leftWingLayout.setLayoutParams(leftWingImageViewLayoutParams);
//				
//				RelativeLayout.LayoutParams rightWingImageViewLayoutParams = (LayoutParams) rightWingView.getLayoutParams();
//				rightWingImageViewLayoutParams.width = contentView.getWidth()/4;
//				rightWingView.setLayoutParams(rightWingImageViewLayoutParams);
			}
		});
		
		sound1 = MediaPlayer.create(PamphletDetailsActivity.this, R.raw.page1_sound);
		sound2 = MediaPlayer.create(PamphletDetailsActivity.this, R.raw.page2_sound);
		leftWingView.post(new Runnable() {

			@Override
			public void run() {
//				RelativeLayout.LayoutParams leftWingLayoutParams = (LayoutParams) leftWingLayout.getLayoutParams();
//				leftWingLayoutParams.width = 2*contentView.getWidth()/3;
//				leftWingLayoutParams.leftMargin = contentView.getWidth()/3;
//				leftWingLayoutParams.height = contentView.getHeight();
//				leftWingLayout.setLayoutParams(leftWingLayoutParams);
				
				RelativeLayout.LayoutParams rightWingImageViewLayoutParams = (LayoutParams) rightWingView.getLayoutParams();
				rightWingImageViewLayoutParams.width = displayWidth/3;
				rightWingImageViewLayoutParams.height = displayHeight;
				rightWingView.setLayoutParams(rightWingImageViewLayoutParams);
				
				RelativeLayout.LayoutParams centerWingImageViewLayoutParams = (LayoutParams) rightWingView.getLayoutParams();
				centerWingImageViewLayoutParams.width = displayWidth/3;
				centerWingImageViewLayoutParams.height = displayHeight;
				centerWingImageView.setLayoutParams(centerWingImageViewLayoutParams);
				centerWingImageView.setImageBitmap(backgroundCenter);
				centerWingImageView.setVisibility(View.VISIBLE);
				RelativeLayout.LayoutParams rightWingViewOnLeftWingLayoutParams = (LayoutParams) rightWingViewOnLeftWing.getLayoutParams();
				rightWingViewOnLeftWingLayoutParams.width = displayWidth/3;
				rightWingViewOnLeftWingLayoutParams.height = displayHeight;
				rightWingViewOnLeftWing.setLayoutParams(rightWingViewOnLeftWingLayoutParams);
				rightWingViewOnLeftWing.setImageBitmap(transitionBitmap);
				rightWingView.setImageBitmap(transitionBitmap);
				
				RelativeLayout.LayoutParams leftWingImageViewLayoutParams = (LayoutParams) leftWingView.getLayoutParams();
				leftWingImageViewLayoutParams.width = displayWidth/3;
				leftWingImageViewLayoutParams.height = displayHeight;
//				leftWingImageViewLayoutParams.leftMargin =  contentView.getWidth()/3;
				leftWingView.setLayoutParams(leftWingImageViewLayoutParams);
				applyRotation(leftWingView, 0, -90, 0, 0, new Animation.AnimationListener() {
					
					@Override
					public void onAnimationStart(Animation animation) {
						sound1.start();
					}
					
					@Override
					public void onAnimationRepeat(Animation animation) {
						
					}
					
					@Override
					public void onAnimationEnd(Animation animation) {
						((ImageView)leftWingView).setImageBitmap(backgroundLeft);
						applyRotation(leftWingView, -90, -180, 0, 0, new Animation.AnimationListener() {
							
							@Override
							public void onAnimationStart(Animation animation) {
								
							}
							
							@Override
							public void onAnimationRepeat(Animation animation) {
								
							}
							
							@Override
							public void onAnimationEnd(Animation animation) {
								
								rightWingViewOnLeftWing.setVisibility(View.INVISIBLE);
								applyRotation(rightWingView, 0, 90, displayWidth/3, 0, new Animation.AnimationListener() {
									
									@Override
									public void onAnimationStart(Animation animation) {
										sound2.start();
									}
									
									@Override
									public void onAnimationRepeat(Animation animation) {
									}
									
									@Override
									public void onAnimationEnd(Animation animation) {
										((ImageView)rightWingView).setImageBitmap(backgroundRight);
										applyRotation(rightWingView, 90, 180, displayWidth/3, 0, new Animation.AnimationListener() {
											
											@Override
											public void onAnimationStart(Animation animation) {
											}
											
											@Override
											public void onAnimationRepeat(Animation animation) {
											}
											
											@Override
											public void onAnimationEnd(Animation animation) {
												showContentAfterAnimation();
											}
										}, new DecelerateInterpolator());
									}
								}, new AccelerateInterpolator());
							}
						}, new DecelerateInterpolator());
//						rightWingViewOnLeftWing.setVisibility(View.INVISIBLE);
//						applyRotation(rightWingView, 0, 180, displayWidth/3, 0, null);
					}
				}, new AccelerateInterpolator());
			}
		});
		/*rightWingView.post(new Runnable() {

			@Override
			public void run() {
//				RelativeLayout.LayoutParams rightWingLayoutParams = (LayoutParams) rightWingLayout.getLayoutParams();
//				rightWingLayoutParams.width = 2*contentView.getWidth()/3;
//				rightWingLayoutParams.height = contentView.getHeight();
//				rightWingLayoutParams.rightMargin =  contentView.getWidth()/3;
//				rightWingLayout.setLayoutParams(rightWingLayoutParams);
				
				RelativeLayout.LayoutParams rightWingImageViewLayoutParams = (LayoutParams) rightWingView.getLayoutParams();
				rightWingImageViewLayoutParams.width = displayWidth/3;
				rightWingImageViewLayoutParams.height = contentView.getHeight();
//				rightWingImageViewLayoutParams.leftMargin =  contentView.getWidth()/3;
				rightWingView.setLayoutParams(rightWingImageViewLayoutParams);
				applyRotation(rightWingView, 0, 180, displayWidth/3, 0);
			}
		});*/
	}
	
	
	
	@SuppressLint("NewApi")
	public void closePamphlet(){
//		RelativeLayout.LayoutParams rightWingImageViewLayoutParams = (LayoutParams) rightWingView.getLayoutParams();
//		rightWingImageViewLayoutParams.width = displayWidth/3;
//		rightWingImageViewLayoutParams.height = displayHeight;
//		rightWingView.setLayoutParams(rightWingImageViewLayoutParams);
//		
//		RelativeLayout.LayoutParams rightWingViewOnLeftWingLayoutParams = (LayoutParams) rightWingViewOnLeftWing.getLayoutParams();
//		rightWingViewOnLeftWingLayoutParams.width = displayWidth/3;
//		rightWingViewOnLeftWingLayoutParams.height = displayHeight;
//		rightWingViewOnLeftWing.setLayoutParams(rightWingViewOnLeftWingLayoutParams);
//		
//		RelativeLayout.LayoutParams leftWingImageViewLayoutParams = (LayoutParams) leftWingView.getLayoutParams();
//		leftWingImageViewLayoutParams.width = displayWidth/3;
//		leftWingImageViewLayoutParams.height = displayHeight;
////		leftWingImageViewLayoutParams.leftMargin =  contentView.getWidth()/3;
//		leftWingView.setLayoutParams(leftWingImageViewLayoutParams);
		contentView.animate().alpha(0).setDuration(400).setListener(new AnimatorListener() {
			
			@Override
			public void onAnimationStart(Animator animation) {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void onAnimationRepeat(Animator animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationEnd(Animator animation) {
				applyRotation(rightWingView, 180, 90, displayWidth/3, 0, new Animation.AnimationListener() {
					
					@Override
					public void onAnimationStart(Animation animation) {
						sound2.start();
					}
					
					@Override
					public void onAnimationRepeat(Animation animation) {
						
					}
					
					@Override
					public void onAnimationEnd(Animation animation) {
						((ImageView)rightWingView).setImageBitmap(transitionBitmap);
						applyRotation(rightWingView, 90, 0, displayWidth/3, 0, new Animation.AnimationListener() {
							
							@Override
							public void onAnimationStart(Animation animation) {
								
							}
							
							@Override
							public void onAnimationRepeat(Animation animation) {
								
							}
							
							@Override
							public void onAnimationEnd(Animation animation) {
								sound2.stop();
								sound2.release();
								rightWingViewOnLeftWing.setVisibility(View.VISIBLE);
								rightWingView.clearAnimation();
								rightWingView.setVisibility(View.INVISIBLE);
								applyRotation(leftWingView, -180, -90, 0, 0, new Animation.AnimationListener() {
									
									@Override
									public void onAnimationStart(Animation animation) {
										sound1.start();
									}
									
									@Override
									public void onAnimationRepeat(Animation animation) {
									}
									
									@Override
									public void onAnimationEnd(Animation animation) {
										((ImageView)leftWingView).setImageBitmap(cover);
										applyRotation(leftWingView, -90, 0, 0, 0, new Animation.AnimationListener() {
											
											@Override
											public void onAnimationStart(Animation animation) {
											}
											
											@Override
											public void onAnimationRepeat(Animation animation) {
											}
											
											@Override
											public void onAnimationEnd(Animation animation) {
												sound1.stop();
												sound1.release();
												finish();
											}
										}, new DecelerateInterpolator());
									}
								}, new AccelerateInterpolator());
							}
						}, new DecelerateInterpolator());
//						rightWingViewOnLeftWing.setVisibility(View.INVISIBLE);
//						applyRotation(rightWingView, 0, 180, displayWidth/3, 0, null);
					}
				}, new AccelerateInterpolator());
			}
			
			@Override
			public void onAnimationCancel(Animator animation) {
				// TODO Auto-generated method stub
				
			}
		});
		
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		loadContentAfterAnimation();

	}
	@SuppressLint("NewApi")
	private void loadContentAfterAnimation() {
		FragmentManager fragmentManager = getFragmentManager();
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		transaction.add(R.id.pamphlet_details_frame_layout, PamphletDetailsFragment.create(pamphlet));
		transaction.commitAllowingStateLoss();
		contentView.setAlpha(0);
	}
	
	
	@SuppressLint("NewApi")
	private void showContentAfterAnimation() {
		contentView.animate().alpha(1).setDuration(400).start();
	}
	
    public void showFavouriteItem(String pamphletId, JSONObject favItem) {
    	if (getFragmentManager().findFragmentByTag(FAVOURITE_ITEM_TAG) == null) {
    		FragmentTransaction transaction = getFragmentManager().beginTransaction();
    		transaction.setCustomAnimations(R.animator.fade_enter, R.animator.fade_exit);
    		transaction.add(R.id.favourite_item_container, FavouriteItemDetailsFragment.create(pamphletId, favItem), FAVOURITE_ITEM_TAG);
    		transaction.commit();	
    	}
    }
	

	private void applyRotation(View mContainer, float start, float end, float centerX, float centerY, Animation.AnimationListener onFinishListener, Interpolator interpolator) {
		// Find the center of the container
		// final float centerX = mContainer.getWidth() / 2.0f;
		// final float centerY = mContainer.getHeight() / 2.0f;

		// Create a new 3D rotation with the supplied parameter
		// The animation listener is used to trigger the next animation
		final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end, centerX, centerY, 0f, true);
		rotation.setDuration(rotationTime);
		rotation.setFillAfter(true);
		rotation.setInterpolator(interpolator);
		if(onFinishListener != null)
			rotation.setAnimationListener(onFinishListener);

		mContainer.startAnimation(rotation);
	}

	private float dipToPixel(int dip) {
		Resources r = getResources();
		return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, r.getDisplayMetrics());
	}
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(backgroundLeft != null ){
			backgroundLeft.recycle();
			backgroundLeft = null;
		}
		if(backgroundCenter != null){
			backgroundCenter.recycle();
			backgroundCenter = null;
		}
		if(backgroundRight != null){
			backgroundRight.recycle();
			backgroundRight = null;
		}
		if(transitionBitmap != null){
			transitionBitmap.recycle();
			transitionBitmap = null;
		}
		if( cover != null){
			cover.recycle();
			cover = null;
		}
	}
}
